import jsonpath
from api.base_api import BaseApi


class CategoryApi(BaseApi):

    def add(self, category_data):
        """增加商品类目"""
        url_add = "admin/category/create"
        r_add = self.send_req("post", url_add, json=category_data)
        return r_add

    def add_by_name(self, category_name):
        """添加指定名称的商品类目"""
        category_data = {"name": category_name, "keywords": "aaa", "level": "L1", "pid": 0, "desc": "bbb",
                         "iconUrl": "", "picUrl": ""}
        return self.add(category_data)

    def get(self):
        """查询商品类目"""
        category_list_url = "admin/category/list"
        r_get = self.send_req("get", category_list_url)
        return r_get

    def get_categoryname_exist(self, name):
        r_get = self.get()
        category_name_list = jsonpath.jsonpath(r_get.json(), "$..list..name")
        return True if name in category_name_list else False

    def get_categoryid_by_name(self, name):
        """通过商品类目名称获取商品类目id"""
        r = self.get()
        category_id = jsonpath.jsonpath(r.json(), f"$..list[?(@.name=='{name}')]..id")[0]
        return category_id

    def update(self, category_data):
        """更新商品类目名称"""
        category_update_url = "admin/category/update"
        r_update = self.send_req("post", category_update_url, json=category_data)
        return r_update

    def delete(self, category_data):
        """删除商品类目"""
        category_delete_url = "admin/category/delete"
        r_del = self.send_req("post", category_delete_url, json=category_data)
        return r_del

    def delete_by_name(self, category_name):
        """通过类目名称删除类目"""
        category_id = self.get_categoryid_by_name(category_name)
        category_data = {"id": category_id, "name": category_name, "keywords": "aaa", "desc": "bbb", "iconUrl": "",
                         "picUrl": "",
                         "level": "L1", "children": [], "preview": [""]}
        return self.delete(category_data)
